package apply_token

import (
	"chain_bridge_service/configs"
	"chain_bridge_service/internal/repository/mongodb/user"
	"context"
	"github.com/pkg/errors"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/bson/primitive"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

func NewModel() *ApplyToken {
	return new(ApplyToken)
}

func (p *ApplyToken) List(db *mongo.Client, pageIndex uint, pageSize uint) (list []ApplyToken, err error) {
	var tokenList []ApplyToken

	cfg := configs.Get().Mongodb
	client := db.Database(cfg.Config.Name).Collection("apply_token")
	userClient := db.Database(cfg.Config.Name).Collection("user")
	skip := int64((pageIndex - 1) * pageSize)
	findOptions := options.Find()
	findOptions.SetSort(bson.D{{"_id", -1}})
	findOptions.SetSkip(skip)
	findOptions.SetLimit(int64(pageSize))
	find, err := client.Find(context.TODO(), bson.D{}, findOptions)
	if err != nil && !errors.Is(err, mongo.ErrNoDocuments) {
		return nil, err
	}

	err = find.All(context.TODO(), &tokenList)
	if err != nil {
		return nil, err
	}
	for i, token := range tokenList {
		userInfo := user.NewModel()
		objId, _ := primitive.ObjectIDFromHex(token.UserId)
		_ = userClient.FindOne(context.TODO(), bson.D{{"_id", objId}}).Decode(&userInfo)
		tokenList[i].UserName = userInfo.Username
		tokenList[i].Email = userInfo.Email
	}

	return tokenList, nil
}

func (p *ApplyToken) Count(db *mongo.Client) (count int64, err error) {
	cfg := configs.Get().Mongodb
	client := db.Database(cfg.Config.Name).Collection("apply_token")
	count, err = client.CountDocuments(context.TODO(), bson.D{})
	if err != nil && !errors.Is(err, mongo.ErrNoDocuments) {
		return 0, err
	}
	return count, nil
}
